const Base = require('../common/base.js');
module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.adpos = this.appModel("position", "ad");
		this.adcon = this.appModel("content", "ad");
	}
	async indexAction() {
		if(this.isGet) {
			return this.appDisplay();
		}
		let posts = this.post();
		let where = {};
		const data = await this.adcon.dataTable(posts, where);
		console.log(data)
		return this.json(data);
	}
	async positionAction() {
		if(this.isGet) {
			return this.appDisplay();
		}
		let posts = this.post();
		let where = {};
		const data = await this.adpos.dataTable(posts, where);
		console.log(data)
		return this.json(data);
	}
	async statusAction() {
		let id = this.post("id");
		let status = this.post("status");
		let row = await this.adcon.setOne(id, {
			status: status
		});
		if(row == 0) {
			return this.fail("修改失败");
		}
		return this.success();
	}
	async addAction() {
		if(this.isGet) {
			let positions = await this.adpos.select();
			this.assign("positions",positions);
			return this.appDisplay();
		}
		let posts = this.post();
		let code = await this.adpos.where({id: posts.position}).getField("code",true);
		console.log(posts);
		await this.adcon.add({
			name: posts.name,
			pic_url: posts.pic_url,
			url: posts.url,
			code: code,
			position_id: posts.position,
			create_time: new Date().valueOf(),
			status: 1
		});
		
		return this.success("发布成功");
		
		
	}
	async editAction() {
		if(this.isGet) {
			let gets = this.get();
			let ad = await this.adcon.findOne(gets.id);
			let positions = await this.adpos.select();
			this.assign("positions",positions);
			this.assign("ad",ad);
			return this.appDisplay();
		}
		let posts = this.post();
		console.log(posts);
		let code = await this.adpos.where({id: posts.position}).getField("code",true);
		await this.adcon.setOne(posts.id,{
			name: posts.name,
			pic_url: posts.pic_url,
			url: posts.url,
			code: code,
			position_id: posts.position,
			
		});
		
		return this.success("修改成功");
		
		
	}
	
	async uploadAction() {
		
		let file = this.file("picture");

		let pics = await this.uploadImage(file, "ad");
		console.log(pics);
		return this.success(pics);
	}
	
	async addposAction() {
		if(this.isGet) {
			
			return this.appDisplay();
		}
		let posts = this.post();
		console.log(posts);
		await this.adpos.add({
			name: posts.name,
			code: posts.code,
			type: posts.type,
			width: posts.width,
			height: posts.height,
			create_time: new Date().valueOf()
		});
		
		return this.success("发布成功");
		
		
	}
	async editposAction() {
		if(this.isGet) {
			let gets = this.get();
			let position = await this.adpos.findOne(gets.id);
			this.assign("position",position);
			return this.appDisplay();
		}
		let posts = this.post();
		console.log(posts);
		await this.adpos.setOne(posts.id,{
			name: posts.name,
			code: posts.code,
			type: posts.type,
			width: posts.width,
			height: posts.height
			
		});
		
		return this.success("修改成功");
		
		
	}
	
};